﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using MINERP.StartOrder.Presenter;
using MINERP.StartOrder.IView;
using MINERP.MODEL.StartOrder;
using MINERP.MODEL.FoundationModel;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraEditors.Repository;
using MINERP.ComControls;
using ServiceInterfaces.DataContracts;
using System.Threading;
using System.Configuration;
using System.Collections;
using System.IO;
using System.Drawing;
using Leadtools.Codecs;
using MINERP.COM;


namespace MINERP.StartOrder.Forms
{
    public partial class FrmMain :FrmParent, IMainView
    {
        private delegate void RefreshMoveOrderHander(List<MoveOrderInfo> moveOrderInfoList);
        private delegate void ShowMsgHander(string msg);
        private delegate void ShowFormMsgHander(string msg);
        private delegate void CloseProcessBarHander();
        private delegate void ShowProcessBarHander();
        GridHitInfo downHitInfo;//gridControls拖曳

        FrmProcessBar bar;//进度条窗体

        private DateTime fechTime;//取件
        private int Priority;//加急级别

        public FrmMainPresenter _presenter;
        private int _userId;

        private string orderBagCode;
        private RasterCodecs codecs;

        public FrmMain()
        {

             _presenter = new FrmMainPresenter(this);
            InitializeComponent();
            _presenter.RefreshMovePhotoProcessEvent += new FrmMainPresenter.RefreshMovePhotoProcessHander(RefreshMoveOrderInfo);
            _presenter.showMoveMsgEvent +=new FrmMainPresenter.ShowMoveMsgHander(showMoveMsgEvent);
            _presenter.showOrderBagCodeEvent +=new FrmMainPresenter.ShowOrderBagCodeHander(_presenter_showOrderBagCodeEvent);
            //_presenter.showFormMsgEvent +=new FrmMainPresenter.ShowFormMsgHander(ShowFormMsgEvent);
            //_presenter.closeProcessBarFormEvent += new FrmMainPresenter.CloseProcessBarFromHander(CloseProcessBarFormEvent);
            //_presenter.showProcessBarFormEvent += new FrmMainPresenter.ShowProcessBarFormHander(ShowProcessBarFormEvent);
            codecs = new RasterCodecs();
        }
        /// <summary>
        /// 析构函数
        /// </summary>
        ~FrmMain()
        {
            codecs.Dispose();
        }

        // form load 事件
        private void FrmMain_Load(object sender, EventArgs e)
        {
            try
            {
                string orderPath = Properties.Settings.Default.OrderLocalPath;
                if (orderPath != "")
                {
                    browser1.SelectPath(orderPath, true);
                }
                _userId = userId;
                cmbPriority.SelectedIndex = 0;
                cmbUnit.SelectedIndex = 0;
                orderBagCode = _presenter.AddOrderBagTemp();//插入占位用的订单包号
                txtOrderBagCode.Text = orderBagCode;

                _presenter.BindShop();

                int shopId = _presenter.ShopList.First(s => s.ShopName == cmbShopList.Text).ShopId;
                _presenter.BindProductTemplete(shopId);
                _presenter.BindPaperType(shopId);
                _presenter.BindPaperFace();
                _presenter.BindAllPrinter();

                _presenter.BindOrderInfoPaperType();
                _presenter.BindOrderInfoPaperFace();

                _presenter.BindPhotoInfoPaperType();
                _presenter.BindPhotInfoPaperFace();

                _presenter.BindUsers();

                ShopInfo_Order currentShopInfo = _presenter.ShopList.First(s => s.ShopName == cmbShopList.Text);

                _presenter.SetCurrentShopInfo(currentShopInfo);
                _presenter.SetUnit(cmbUnit.Text);

                //后台加载产品模版
                backgroundLoadProductTemplete.RunWorkerAsync();
                ////移动照片
                //Thread th = new Thread(new ThreadStart(_presenter.MovePhotoToServer));
                    
                //th.IsBackground = true;
                //th.Start();

                //_presenter.SetTcpConnect();//设置tcp连接
                GetCRCConfig();//获取crc配置
                _presenter.SetCheckCRC(chkCheckRepeatOrder.Checked);//设定是否检查重复开单

                gcOrderProductInfo.DataSource = new List<OrderInfo>();
                LoadGridViewLayout();
                DataTransfer.CopyRule = Properties.Settings.Default.StringCopyRule;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message,"提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
            }

        }
        private void LoadGridViewLayout()
        {
            string StartOrdergvProductListPath = Application.StartupPath + "\\Layout\\StartOrdergvProductList.Xml";
            string StartOrdergvProductPath = Application.StartupPath + "\\Layout\\StartOrdergvProduct.Xml";

            if (File.Exists(StartOrdergvProductListPath))
            {
                gvOrderProductInfo.RestoreLayoutFromXml(StartOrdergvProductListPath);
            }
            if (File.Exists(StartOrdergvProductPath))
            {
                gvPhoto.RestoreLayoutFromXml(StartOrdergvProductPath);
            }
        }
        /// <summary>
        /// 刷新gcMovephoto 
        /// </summary>
        /// <param name="moveOrderInfoList"></param>
        void RefreshMoveOrderInfo(List<MoveOrderInfo> moveOrderInfoList)
        {
            if (this.InvokeRequired)
            {
                RefreshMoveOrderHander refreshMoveOrderHander = new RefreshMoveOrderHander(RefreshMoveOrderInfo);
                this.Invoke(refreshMoveOrderHander, new object[] { moveOrderInfoList });
            }
            else
            {
                gcMovePhoto.DataSource = moveOrderInfoList;
                gcMovePhoto.RefreshDataSource();
            }

        }

        //刷新lbMessage
        void showMoveMsgEvent(string msg)
        {
            if (this.InvokeRequired)
            {
                if (!this.Disposing)
                {
                    this.Invoke(new ShowMsgHander(showMoveMsgEvent), new object[] { msg });
                }
            }
            else
            {
                lbMessage.Items.Insert(0, msg);
            }
        }

        //向主窗体弹出消息提示
        void ShowFormMsgEvent(string msg)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new ShowFormMsgHander(ShowFormMsgEvent),new object []{msg});
            }
            else
            {
                MessageBox.Show(msg, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        //刷新订单号
        void _presenter_showOrderBagCodeEvent(string msg)
        {
            if (this.InvokeRequired)
            {
                if (!this.Disposing)
                {
                    this.Invoke(new MINERP.StartOrder.Presenter.FrmMainPresenter.ShowOrderBagCodeHander(_presenter_showOrderBagCodeEvent), new object[] { msg });
                }
            }
            else
            {
                txtOrderBagCode.Text = msg;
            }

        }

        //显示进度条
        void ShowProcessBarFormEvent()
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new ShowProcessBarHander(ShowProcessBarFormEvent));
            }
            else
            {
                bar = new FrmProcessBar();
                bar.ShowDialog();
            }
        }

        //关闭进度条
        void CloseProcessBarFormEvent()
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new CloseProcessBarHander(CloseProcessBarFormEvent));
            }
            else
            {
                bar.Close();
            }
        }

        //拖拽接收数据
        private void gcProductInfo_DragDrop(object sender, DragEventArgs e)
        {
            try
            {
                gvOrderProductInfo.FocusedRowChanged -= gvOrderProductInfo_FocusedRowChanged; //拖动期间取消rowchanged事件
                if (e.Data.GetDataPresent(DataFormats.FileDrop))
                {
                    var filePath = e.Data.GetData(DataFormats.FileDrop);//获取拖拽过来的文件夹列表
                    string[] fileArry = (string[])filePath;
                    foreach (var item in fileArry)
                    {
                        if (File.Exists(item))
                        {
                            string fileFolder = Path.GetDirectoryName(item);

                            if (fileFolder == Properties.Settings.Default.OrderLocalPath)
                            {
                                MessageBox.Show("文件开单，缺少一层文件夹!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                return;
                            }
                        }
                        _presenter.BindOrderProduct(item, Properties.Settings.Default.OrderBYCtmFolder); 
                    }
                   
                }
                else
                {
                    ProductTempleteInfo product = e.Data.GetData("list") as ProductTempleteInfo;
                    Point p1 = gcOrderProductInfo.PointToClient(new Point(e.X, e.Y));                //
                    DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo info = gvOrderProductInfo.CalcHitInfo(p1);
                    if (((List<OrderInfo>)(gcOrderProductInfo.DataSource)).Count == 0 || !info.InRow)
                    {
                        OrderInfo oi = _presenter.AddGoodsOrderInfo(product);
                    }
                    else
                    {
                      
                        //OrderInfo orderInfo = gvOrderProductInfo.GetRow(info.RowHandle) as OrderInfo;
                        int [] rowHandles = gvOrderProductInfo.GetSelectedRows();
                        if (rowHandles.Length > 1)
                        {
                            foreach (var rowhandle in rowHandles)
                            {
                                OrderInfo orderInfo = gvOrderProductInfo.GetRow(rowhandle) as OrderInfo;
                                if (orderInfo.IsExistProductTemplete)
                                {
                                    MessageBox.Show("模版已存在!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                }
                                else
                                {
                                    _presenter.BindOrderInfoAndProductTemplete(orderInfo, product);//绑定照片和模版
                                    BindWorkFlowList(orderInfo);

                                    ComputeYJCompleteTime();//计算完成时间
                                }

                            }
                        }
                        else
                        {
                            OrderInfo orderInfo = gvOrderProductInfo.GetRow(info.RowHandle) as OrderInfo;
                            if (orderInfo.IsExistProductTemplete)
                            {
                                MessageBox.Show("模版已存在!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                            else
                            {
                                _presenter.BindOrderInfoAndProductTemplete(orderInfo, product);//绑定照片和模版
                                BindWorkFlowList(orderInfo);

                                ComputeYJCompleteTime();//计算完成时间
                            }

                        }
                       

                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            finally
            {
                gvOrderProductInfo.FocusedRowChanged += gvOrderProductInfo_FocusedRowChanged; //拖动完成恢复rowchanged事件
            }
      
        }

        //拖拽接受格式
        private void gcProductInfo_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.Move;
            else if (e.Data.GetDataPresent("list"))
            {
                e.Effect = DragDropEffects.Move;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        #region IMainView接口成员

        /// <summary>
        /// 当前商户纸型
        /// </summary>
        public PaperType_Info PaperTypeInfo
        {
            get
            {
                return cmbPaperType.SelectedItem as PaperType_Info;
            }
        }

        /// <summary>
        /// 当前商户纸面
        /// </summary>
        public PaperFace_Info PaperFaceInfo
        {
            get
            {
                return cmbPaperFace.SelectedItem as PaperFace_Info;
            }
        }

        /// <summary>
        /// 开单用户Id
        /// </summary>
        public   int UserId 
        { 
            get
            {
                return _userId;
                //return userId;
            }

        }

        /// <summary>
        /// 开单是否成功
        /// </summary>
        public bool OrderSuccessfull { get; set; }


        /// <summary>
        /// 订单包
        /// </summary>
        public  string OrderBagCode { get; set; }
        /// <summary>
        /// 是否有文件在上传
        /// </summary>
        public bool IsUploadPhoto { get; set; }

        /// <summary>
        /// 绑定有效商户
        /// </summary>
        /// <param name="listShop"></param>
        public void BindShop(List<ShopInfo_Order> listShop)
        {
            cmbShopList.Items.Clear();
            foreach (var item in listShop)
            {
                cmbShopList.Items.Add(item.ShopName);
            }
            if (cmbShopList.Items.Count > 0)
            {
                cmbShopList.SelectedIndex = 0;
            }
            //cmbShopList.DataSource = listShop;
            //cmbShopList.DisplayMember = "ShopName";
            //cmbShopList.ValueMember = "MnemonicCode";
            //绑定对象很慢
            
        }
        /// <summary>
        /// 选中商户
        /// </summary>
        /// <param name="ShopName"></param>
       public  void SelectShop(string ShopName) 
       {
           cmbShopList.SelectedItem = ShopName;
       }
       public void ClearShopMin()
       {
           txtShopMnemonicCode.Text = "";
       }
        /// <summary>
        /// 绑定产品文件夹
        /// </summary>
        /// <param name="listOrderInfo"></param>
        public void BindOrderProduct(List<OrderInfo> listOrderInfo,bool flag)
        {
            gcOrderProductInfo.DataSource = listOrderInfo;
            gcOrderProductInfo.RefreshDataSource();

            if (listOrderInfo.Count > 0)
                BindPhotoList(listOrderInfo.First());
            else
                ClearPhotoList();
            if (flag)//有产品或照片在待开单列表中
            {
                MessageBox.Show("有产品照片已经在开单区！","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
            }
        }

        /// <summary>
        /// 绑定商户产品模版
        /// </summary>
        /// <param name="listProductTemplete"></param>
        public void BindProudctTemplete(List<ProductTempleteInfo> listProductTemplete)
        {
            gcProductTemplate.DataSource = listProductTemplete;
            gcProductTemplate.RefreshDataSource();
        }


        /// <summary>
        /// 绑定商户已勾选纸型
        /// </summary>
        /// <param name="listPaperTypeInfo"></param>
        public  void BindShopPaperType(List<PaperType_Info> listPaperTypeInfo)
        {
            try
            {
                cmbPaperType.DataSource = listPaperTypeInfo;
                cmbPaperType.DisplayMember = "Name";
                cmbPaperType.ValueMember = "PaperTypeID";

                ShopInfo_Order shopInfo = _presenter.ShopList.First(s => s.ShopName == cmbShopList.Text);
                if (shopInfo.PaperTypeId != 0)
                {
                    cmbPaperType.SelectedItem = ((List<PaperType_Info>)cmbPaperType.DataSource).First(p => p.PaperTypeID == shopInfo.PaperTypeId);
                }


                cmbPaperType.Refresh();
            }
            catch
            {
                MessageBox.Show("商户默认纸型还未设置价格!","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
            }

        }

        /// <summary>
        /// 绑定有效纸面
        /// </summary>
        /// <param name="listPaperFaceInfo"></param>
        public  void BindPaperFace(List<PaperFace_Info> listPaperFaceInfo)
        {
            cmbPaperFace.DataSource = listPaperFaceInfo;
            cmbPaperFace.DisplayMember = "Name";
            cmbPaperFace.ValueMember = "PaperFaceID";


            ShopInfo_Order shopInfo = _presenter.ShopList.First(s => s.ShopName == cmbShopList.Text);
            if (shopInfo.PaperFaceId != 0)
            {
                cmbPaperFace.SelectedItem = ((List<PaperFace_Info>)cmbPaperFace.DataSource).First(p => p.PaperFaceID == shopInfo.PaperFaceId);
            }
            

            cmbPaperFace.Refresh();
        }

        /// <summary>
        /// 绑定产品纸型
        /// </summary>
        /// <param name="listPaperType"></param>
        public void BindOrderInfoPaperType(List<PaperType_Info> listPaperType)
        {
            cmbOrderInfoPaperType.Items.Clear();
            foreach (var item in listPaperType)
            {
                cmbOrderInfoPaperType.Items.Add(item.Name);
            }
        }

        /// <summary>
        /// 绑定产品纸面
        /// </summary>
        /// <param name="listPaperFace"></param>
        public  void BindOrderInfoPaperFace(List<PaperFace_Info> listPaperFace)
        {
            cmbOrderInfoPaperFace.Items.Clear();
            foreach (var item in listPaperFace)
            {
                cmbOrderInfoPaperFace.Items.Add(item.Name);
            }
        }

        /// <summary>
        /// 绑定照片纸型
        /// </summary>
        /// <param name="listPaperType"></param>
        public void BindPhotoInfoPaperType(List<PaperType_Info> listPaperType)
        {
            cmbPhotoInfoPaperType.Items.Clear();
            foreach (var item in listPaperType)
            {
                cmbPhotoInfoPaperType.Items.Add(item.Name);
            }
        }

        /// <summary>
        /// 绑定照片纸面
        /// </summary>
        /// <param name="listPaperFace"></param>
        public void BindPhotoInfoPaperFace(List<PaperFace_Info> listPaperFace)
        {
            cmbPhotoInfoPaperFace.Items.Clear();
            foreach (var item in listPaperFace)
            {
                cmbPhotoInfoPaperFace.Items.Add(item.Name);
            }
        }

        /// <summary>
        /// 绑定全部有效纸型
        /// </summary>
        /// <param name="_userList"></param>
        public void BindUserInfoList(List<User_Info> userList)
        {
            cmbUsers.Items.Clear();
            foreach (var item in userList)
            {
                cmbUsers.Items.Add(item.UserName);
            }
        }


        /// <summary>
        /// 加载开单界面时绑定所有打印机
        /// </summary>
        /// <param name="printerList"></param>
        public  void BinAllPrinter(List<ServiceInterfaces.DataContracts.Printer_Info> printerList)
        {
            cmbPrinter.Items.Clear();
            foreach (var item in printerList)
            {
                cmbPrinter.Items.Add(item.PName);
            }
        }

        /// <summary>
        /// 绑定打印机
        /// </summary>
        /// <param name="printerList"></param>
        public void BindPrinter(List<ServiceInterfaces.DataContracts.Printer_Info> printerList)
        {
            repositoryItemComboBoxPrinter.Items.Clear();
            foreach (var item in printerList)
            {
                repositoryItemComboBoxPrinter.Items.Add(item.PName);
            }
        }

        /// <summary>
        /// 绑定委外商
        /// </summary>
        /// <param name="outshopList"></param>
        public void BindOutShop(List<OutProcessShopInfo> outshopList)
        {
            repositoryItemComboBoxOutShop.Items.Clear();
            foreach (var item in outshopList)
	        {
        		 repositoryItemComboBoxOutShop.Items.Add(item.OutShopName);
	        }
            //OutProcessShopInfo outshop = outshopList.FirstOrDefault(o=>o.IsDefaultOurProcessShop =true);
            //if (outshop != null)
            //    repositoryItemComboBoxOutShop.NullText = outshop.OutShopName;
        }

        /// <summary>
        /// 绑定附件收费项目列表
        /// </summary>
        /// <param name="CommonChargeNameList"></param>
        public void BindCommonChargeItem(List<CommonChargeItemInfo> CommonChargeInfoList)
        {
            repositoryItemCheckedCmbCommonChargeItem.Items.Clear();
            foreach (var item in CommonChargeInfoList)
            {   
                repositoryItemCheckedCmbCommonChargeItem.Items.Add(item.ItemName);
                int i =repositoryItemCheckedCmbCommonChargeItem.Items.Count;
                if (item.IsUsefull)
                {
                    repositoryItemCheckedCmbCommonChargeItem.Items[i - 1].CheckState = CheckState.Checked;
                }
                else
                {
                    repositoryItemCheckedCmbCommonChargeItem.Items[i - 1].CheckState = CheckState.Unchecked;
                }

            }
        }

        /// <summary>
        /// 设置附加收费项目
        /// </summary>
        /// <param name="techCommonChargeItemInfo"></param>
        public void SetCommonChargeItem(List<TechCommonChargeItemInfo> techCommonChargeItemInfo,List<WorkOrderFlowListInfo> workFlowInfoList)
        {
            string str = string.Empty;
            foreach (DevExpress.XtraEditors.Controls.CheckedListBoxItem item in repositoryItemCheckedCmbCommonChargeItem.Items)
            {

                if (techCommonChargeItemInfo.Exists(t => t.CommonChargeItemName == item.Value.ToString()))
                {
                    int techId = techCommonChargeItemInfo.First(t => t.CommonChargeItemName == item.Value.ToString()).TechId;
                    if (workFlowInfoList.First(w => w.TechId == techId).IsUsefull)
                    {
                        item.CheckState = CheckState.Checked;
                        if (str != string.Empty)
                            str += ",";
                        str += item.ToString();
                    }
                    else
                    {
                        item.CheckState = CheckState.Unchecked;
                    }
                }
                else
                {
                    item.CheckState = CheckState.Unchecked;
                }
            }

            str = str.TrimEnd(',');
            str = str.TrimStart(',');

            ((OrderInfo)gvOrderProductInfo.GetFocusedRow()).CommonChargeItemNames = str;
        }

        /// <summary>
        /// 绑定等待移动产品列表
        /// </summary>
        /// <param name="moveOrderInfoList"></param>
        public void BindMoveOrderInfo(List<MoveOrderInfo> moveOrderInfoList)
        {
            gcMovePhoto.DataSource = moveOrderInfoList;
            gcMovePhoto.RefreshDataSource();
        }

        /// <summary>
        /// 刷新待开单产品
        /// </summary>
        public void RefreshOrderInfo()
        {
            gcOrderProductInfo.RefreshDataSource();
        }

        /// <summary>
        /// 刷新待开单产品照片
        /// </summary>
        public void RefreshPhotoInfo()
        {
            gcPhotoInfo.RefreshDataSource();
        }
         

        #endregion

        //单击产品绑定照片列表
        private void gvProductInfo_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            OrderInfo oi = gvOrderProductInfo.GetRow(e.RowHandle) as OrderInfo;
            BindPhotoList(oi);//绑定照片列表
            BindWorkFlowList(oi);//绑定产品列表
            double wucha = Properties.Settings.Default.PhotoWuCha/2.54;//转换成英寸

            if(oi.Photos.Count >0&&!oi.IsExistProductTemplete)//产品包含照片
            {
                if (e.Column.FieldName == "OrderProductName")
                {
                    var phots = oi.Photos.GroupBy(p => p.PhotoWH);
                   
                    int max = 0;
                    string myKey = "";
                    foreach (var g in phots)
                    {
                        if (g.Count() > max)
                        {
                            max = g.Count();
                            myKey = g.Key;
                        }
                    }
                    PhotoInfo photo = phots.First(p => p.Key == myKey).ToList().First();
                    List<ProductTempleteInfo> list = _presenter.FastSearchProductTemplete(oi.OrderProductName, photo.Height, photo.Width, wucha);
                    if (list.Count > 0)
                    {
                        FrmFastSearchTemplete frm = new FrmFastSearchTemplete(oi,list);
                        frm.ShowDialog(this);
                    }
                }
            }
        }

        /// <summary>
        /// 绑定照片列表
        /// </summary>
        /// <param name="oi"></param>
        private void BindPhotoList(OrderInfo oi)
        {
            if (oi != null)
            {
                gcPhotoInfo.DataSource = oi.Photos.Where(p => p.isPictrue == true).ToList();
                gcPhotoInfo.RefreshDataSource();
            }
            else
            {
                gcPhotoInfo.DataSource = null;
                gcPhotoInfo.RefreshDataSource();
            }

        }
        /// <summary>
        /// 刷新照片的尺寸信息
        /// </summary>
        /// <param name="oi"></param>
        public void RefreshPhotoInfo(OrderInfo oi)
        {
            if (Properties.Settings.Default.PhotoWuCha >= 0)
            {
                double wuchaInch=Properties.Settings.Default.PhotoWuCha/2.54;
                if (oi != null)
                {
                    if (oi.ProductTypeCode == 1 || oi.ProductTypeCode == 2)
                    {
                        oi.Photos.ForEach(ec =>
                        {
                            bool isMatch = false;

                            if (Math.Abs(oi.Width * 2 - ec.Width) < wuchaInch && Math.Abs(oi.Height - ec.Height) < wuchaInch || Math.Abs(oi.Height * 2 - ec.Width) < wuchaInch && Math.Abs(oi.Width - ec.Height) < wuchaInch)
                            {
                                isMatch = true;
                            }
                            if (Math.Abs(oi.Width - ec.Width) < wuchaInch && Math.Abs(oi.Height - ec.Height) < wuchaInch || Math.Abs(oi.Height - ec.Width) < wuchaInch && Math.Abs(oi.Width - ec.Height) < wuchaInch)
                            {
                                isMatch = true;
                            }
                            if (Math.Abs(oi.CoverWidth - ec.Width) < wuchaInch && Math.Abs(oi.CoverHeight - ec.Height) < wuchaInch || Math.Abs(oi.CoverHeight - ec.Width) < wuchaInch && Math.Abs(oi.CoverWidth - ec.Height) < wuchaInch)
                            {
                                isMatch = true;
                            }

                            if (!isMatch)
                            {
                                //WriteLogForCheck.WriteLogFile("不匹配：CoverWidth:" + oi.CoverWidth + ",Width:" + ec.Width +
                                //                              ",CoverHeight" + oi.CoverHeight + ",Height" + ec.Height +
                                //                              ",wuchaInch:" + wuchaInch);
                                ec.isNotSizeInProduct = true;
                            }
                            else
                            {
                                //WriteLogForCheck.WriteLogFile("正常：CoverWidth:" + oi.CoverWidth + ",Width:" + ec.Width +
                                //                          ",CoverHeight" + oi.CoverHeight + ",Height" + ec.Height +
                                //                          ",wuchaInch:" + wuchaInch);
                            }
                        });
                    }
                }
                else
                {
                    gcPhotoInfo.DataSource = null;
                    
                }
            }
            else
            {
                if (oi != null)
                {
                    gcPhotoInfo.DataSource = oi.Photos.Where(p => p.isPictrue == true).ToList();
                    //gcPhotoInfo.RefreshDataSource();
                }
                else
                {
                    gcPhotoInfo.DataSource = null;
                    //gcPhotoInfo.RefreshDataSource();
                }
            }
            gcPhotoInfo.RefreshDataSource();
        }
        /// <summary>
        /// 绑定产品流程
        /// </summary>
        /// <param name="oi"></param>
        private void BindWorkFlowList(OrderInfo oi)
        {
            if (oi != null)
            {
                gcWorkFlow.DataSource = oi.workFlows;
                gcWorkFlow.RefreshDataSource();
            }
            else
            {
                gcWorkFlow.DataSource = null;
                gcWorkFlow.RefreshDataSource();
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            _presenter.ClearOrderProduct();//清楚产品列表
            ClearPhotoList();
        }

        /// <summary>
        /// 清除照片列表
        /// </summary>
        private void ClearPhotoList()
        {
            gcPhotoInfo.DataSource = null;
            gcPhotoInfo.RefreshDataSource();
        }

        //切换商户
        private void cmbShopList_SelectedIndexChanged(object sender, EventArgs e)
        {
            //////Cursor = Cursors.WaitCursor;
            //////try
            //////{
            //////    ShopInfo_Order shop = _presenter.ShopList.First(s => s.ShopName == cmbShopList.Text);
            //////    _presenter.BindProductTemplete(shop.ShopId);
            //////    _presenter.BindPaperType(shop.ShopId);
            //////    _presenter.BindPaperFace();
            //////    _presenter.SetCurrentShopInfo(shop);
            //////    _presenter.ClearOrderProduct();
            //////}
            //////catch (Exception ex)
            //////{
            //////    MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //////}
            //////finally
            //////{
            //////    Cursor = Cursors.Default;
            //////}
            Cursor = Cursors.WaitCursor;
            try
            {
                ShopInfo_Order shop = _presenter.ShopList.First(s => s.ShopName == cmbShopList.Text);
                _presenter.BindProductTemplete(shop.ShopId);
                _presenter.BindPaperType(shop.ShopId);
                _presenter.BindPaperFace();
                //_presenter.BindPhotoInfoPaperType();
                //_presenter.BindPhotInfoPaperFace();

                _presenter.SetCurrentShopInfo(shop);
                _presenter.ClearOrderProduct();
                cmbPriority.Text = shop.Priority.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }

        //刷新商户产品模版
        private void lnklbRefreshProductTemplete_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            try
            {
                _presenter.RefreshShopProductTemplete(_presenter.ShopList.First(s=>s.ShopName ==cmbShopList.Text).ShopId);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message,"提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }

        //助记码搜素产品模版
        private void txtMnemonicCode_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                _presenter.SearchProductTempleteByMnemonicCode(txtMnemonicCode.Text.ToUpper().Trim(), _presenter.ShopList.First(s=>s.ShopName ==cmbShopList.Text).ShopId);
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message,"提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
            }
        }

        //助记码搜索商户
        private void txtShopMnemonicCode_EditValueChanged(object sender, EventArgs e)
        {
            _presenter.SearchShopByMnemonicCode(txtShopMnemonicCode.Text.ToUpper().Trim());
        }


        //刷新商户
        private void tssbtnRefreshShop_Click(object sender, EventArgs e)
        {
            _presenter.BindShop();
        }

        //变换单位
        private void cmbUnit_SelectedValueChanged(object sender, EventArgs e)
        {
            _presenter.SetUnit(cmbUnit.Text);
            if (cmbShopList.Text !=string.Empty)
                _presenter.ChangeUnit(_presenter.ShopList.First(s=>s.ShopName ==cmbShopList.Text).ShopId);

        }
        private void ProductTemplate_MouseDown(object sender, MouseEventArgs e)
        {
            try
            {
                downHitInfo = null;
                GridView view = sender as GridView;
                GridHitInfo hitInfo = view.CalcHitInfo(e.X, e.Y);
                if (ModifierKeys != Keys.None) return;
                if (e.Button == MouseButtons.Left && hitInfo.InRow && hitInfo.HitTest != GridHitTest.RowIndicator)
                    downHitInfo = hitInfo;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

        }

        private void ProductTemplate_MouseMove(object sender, MouseEventArgs e)
        {
            try
            {
                GridView view = sender as GridView;
                if (e.Button == MouseButtons.Left && downHitInfo != null)
                {
                    System.Drawing.Size dragSize = SystemInformation.DragSize;
                    Rectangle rec = new Rectangle(new Point(downHitInfo.HitPoint.X - dragSize.Width / 2, downHitInfo.HitPoint.Y - dragSize.Height / 2), dragSize);
                    if (!rec.Contains(e.X, e.Y))
                    {
                        int[] rows = view.GetSelectedRows();

                        if (rows.Length > 0)
                        {
                            if (!view.IsGroupRow(rows[0]))
                            {
                                ProductTempleteInfo product = (ProductTempleteInfo)view.GetRow(rows[0]);
                                //int pid = product.ProuctId;
                                List<string> pids = new List<string>();
                                //pids.Add(pid.ToString());
                                DataObject data = new DataObject();
                                data.SetData("list", product);
                                DoDragDrop(data, DragDropEffects.All);
                                downHitInfo = null;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //后台线程加载产品模版

        private void backgroundLoadProductTemplete_DoWork(object sender, DoWorkEventArgs e)
        {
            _presenter.BackgroundLoadProductTemplete();
        }


        //设置待开单产品列表样式
        private void gvOrderProductInfo_RowStyle(object sender, RowStyleEventArgs e)
        {
            OrderInfo oi = gvOrderProductInfo.GetRow(e.RowHandle) as OrderInfo;
            if (oi != null)
            {
                if (oi.IsExistProductTemplete)
                {
                    e.Appearance.BackColor = Color.GreenYellow;
                    e.Appearance.BackColor2 = Color.GreenYellow;
                }
            }
        }


        //设置流程列表样式
        private void gvWorkflow_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            WorkOrderFlowListInfo workflow = gvWorkflow.GetRow(e.RowHandle) as WorkOrderFlowListInfo;
            if (workflow != null)
            {
                if (workflow.IsUsefull)
                {
                    e.Appearance.BackColor = Color.GreenYellow;
                    e.Appearance.BackColor2 = Color.GreenYellow;
                }
            }
        }

        //附加收费
        private void repositoryItemCheckedCmbCommonChargeItem_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
        {
            OrderInfo oi = gvOrderProductInfo.GetFocusedRow() as OrderInfo;
            //List<string> CommonChargeItemNameList = new List<string>();
            string str = "";
            string remark ="";
            string strSysMark = "*";//*标志是系统自动加

            foreach (DevExpress.XtraEditors.Controls.CheckedListBoxItem item in repositoryItemCheckedCmbCommonChargeItem.Items)
            {
                if (item.CheckState.ToString() == "Checked")
                {
                    if (str != string.Empty)
                        str += ",";
                    str += item.ToString();
                    remark +=strSysMark+item.ToString();
                    
                    //CommonChargeItemNameList.Add(item.ToString());
                }
                if (oi.Remark.Contains(strSysMark + item.ToString()))
                {
                    oi.Remark = oi.Remark.Replace(strSysMark + item.ToString(), "");
                }

            }
            str = str.TrimEnd(',');
            str = str.TrimStart(',');
            oi.CommonChargeItemNames = str;


            oi.Remark = remark+oi.Remark;
            gvOrderProductInfo.RefreshData();
        }





        //产品换行事件
        private void gvOrderProductInfo_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            OrderInfo oi = gvOrderProductInfo.GetRow(e.FocusedRowHandle) as OrderInfo;
            BindPhotoList(oi);//绑定照片列表
            BindWorkFlowList(oi);//绑定产品列表
        }

        //开单
        private void btnOrder_Click(object sender, EventArgs e)
        {
            if (!bwOrder.IsBusy)
            {
                fechTime = dtFechTime.Value;
                Priority = Convert.ToInt32(cmbPriority.Text.Trim());

                if (((List<OrderInfo>)gcOrderProductInfo.DataSource).Count > 0)
                {
                    int ret = _presenter.CheckOrder();
                    if (ret == 0)
                    {
                        try
                        {
                            bwOrder.RunWorkerAsync();//运行开单线程
                            bar = new FrmProcessBar();
                            bar.ShowDialog(this);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                    if (ret == 1)
                    {
                        MessageBox.Show("还有产品未拖模版！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    if (ret == 2)
                    {
                        MessageBox.Show("还有成品产品未勾选！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                else
                {
                    MessageBox.Show("没有产品！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            else
            {
                MessageBox.Show("请稍等,正在保存上一订单数据！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        //取消开单
        public void Cancelorder()
        {
            try
            {
                bwOrder.CancelAsync();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message,"提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
            }
        }

        //删除待开单区中选中的产品
        private void tssbtnDelete_Click(object sender, EventArgs e)
        {
            OrderInfo oi = gvOrderProductInfo.GetFocusedRow() as OrderInfo;
            _presenter.DeleteSelectOrder(oi);
            ComputeYJCompleteTime();
        }

        private void bwOrder_DoWork(object sender, DoWorkEventArgs e)
        {
           
            
            _presenter.Order(sender,e,fechTime, Priority);
        }

        private void bwOrder_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            bar.Close();
            bar.Dispose();
            _presenter.RefreshOrderProduct();
            bwDeleteEmptyFolder.RunWorkerAsync();
            if (OrderSuccessfull)
            {
                MessageBox.Show("开单成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void tsbtnModifyPhotoNum_Click(object sender, EventArgs e)
        {

        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.IsUploadPhoto)
            {
                MessageBox.Show("还有文件未上传完成请不要关闭开单！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                e.Cancel = true;

            }
            else
            {
                _presenter.DeleteTempOrderBag();//删除占位订单包
            }
        }

     
        private void cmbPaperFace_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (gcOrderProductInfo.DataSource != null)
            {

                foreach (var orderInfo in ((List<OrderInfo>)gcOrderProductInfo.DataSource).ToList())
                {
                    orderInfo.PaperFaceName = cmbPaperFace.Text;
                    foreach (var photo in orderInfo.Photos)
                    {
                        photo.PaperFaceName = cmbPaperFace.Text;
                    }
                }
                gcOrderProductInfo.RefreshDataSource();
                gcPhotoInfo.RefreshDataSource();
            }
         
        }

        private void cmbPaperType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (gcOrderProductInfo.DataSource != null)
            {
                foreach (var orderInfo in ((List<OrderInfo>)gcOrderProductInfo.DataSource).ToList())
                {
                    orderInfo.PapeTypeName = cmbPaperType.Text;
                    foreach (var photo in orderInfo.Photos)
                    {
                        photo.PaperTypeName = cmbPaperType.Text;
                    }
                }
                gcOrderProductInfo.RefreshDataSource();
                gcPhotoInfo.RefreshDataSource();
            }
        }

        private void cmbOrderInfoPaperType_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
        {
            OrderInfo oi = gvOrderProductInfo.GetFocusedRow() as OrderInfo;
            string paperTypeName  = ((DevExpress.XtraEditors.ComboBoxEdit)sender).SelectedItem.ToString();

            foreach (var item in oi.Photos)
            {
                item.PaperTypeName = paperTypeName;
            }
            gcPhotoInfo.RefreshDataSource();
        }

        private void cmbOrderInfoPaperFace_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
        {
            OrderInfo oi = gvOrderProductInfo.GetFocusedRow() as OrderInfo;
            string paperFaceName = ((DevExpress.XtraEditors.ComboBoxEdit)sender).SelectedItem.ToString();
            foreach (var item in oi.Photos)
            {
                item.PaperFaceName = paperFaceName;
            }
            gcPhotoInfo.RefreshDataSource();
        }

        //计算预计完成时间
        private void ComputeYJCompleteTime()
        {
            List<OrderInfo> orderInfoList = gcOrderProductInfo.DataSource as List<OrderInfo>;
            double maxHour = 0;
            foreach (OrderInfo oi in orderInfoList)
            {
                if (oi.workFlows != null)
                {
                    double tempH = 0;
                    foreach (var t in oi.workFlows)
                    {
                        if (t.IsUsefull == true)
                            tempH += t.TechTime;
                    }
                    if (tempH > maxHour)
                        maxHour = tempH;
                }
            }
            DateTime YJTime = DateTime.Now.AddHours(maxHour);
            dtFechTime.Text = YJTime.ToString("yyyy-MM-dd HH:mm");
        }

        private void browser1_Load(object sender, EventArgs e)
        {

        }

        private void gcOrderProductInfo_DragOver(object sender, DragEventArgs e)
        {
            try
            {
                Point p1 = gcOrderProductInfo.PointToClient(new Point(e.X, e.Y));                //
                DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo info = gvOrderProductInfo.CalcHitInfo(p1);
                if (info.InRow)
                {
                    gvOrderProductInfo.FocusedRowHandle = info.RowHandle;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }




        /// <summary>
        /// 选择或取消流程时更新绑定的附加收费项目
        /// </summary>
        /// <param name="techCommonChargeItemList">该节点所绑定的附加收费项目</param>
        /// <param name="IsSelect">节点是否选中</param>
        private void  UpdateCommonChargeItems(List<TechCommonChargeItemInfo> techCommonChargeItemList,bool IsSelect,OrderInfo oi)
        {
            try
            {
                foreach (var techCommonCharge in techCommonChargeItemList)
                {
                    foreach (DevExpress.XtraEditors.Controls.CheckedListBoxItem item in repositoryItemCheckedCmbCommonChargeItem.Items)
                    {
                        if (techCommonCharge.CommonChargeItemName == item.Value.ToString())
                        {
                            if (IsSelect)
                            {
                                item.CheckState = CheckState.Checked;
                                if (!oi.CommonChargeItemNames.Contains(item.Value.ToString()))
                                {
                                    if (oi.CommonChargeItemNames != string.Empty)
                                        oi.CommonChargeItemNames += ",";
                                    oi.CommonChargeItemNames += item.ToString();
                                }
                            }
                            else
                            {
                                item.CheckState = CheckState.Unchecked;
                                if (oi.CommonChargeItemNames.Contains(item.Value.ToString()))
                                {
                                     oi.CommonChargeItemNames =oi.CommonChargeItemNames.Replace(item.Value.ToString(), "");
                                }
                            }
                        }
                    }

                }
                string strcom = oi.CommonChargeItemNames;
                strcom = strcom.Trim();
                strcom =strcom.TrimStart(',');
                strcom =strcom.TrimEnd(',');

                oi.CommonChargeItemNames = strcom;

                gcOrderProductInfo.RefreshDataSource();
            }
            catch
            {

            }
        }

        private void gvWorkflow_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            OrderInfo oi = gvOrderProductInfo.GetFocusedRow() as OrderInfo;
            WorkOrderFlowListInfo workInfo = gvWorkflow.GetRow(e.RowHandle) as WorkOrderFlowListInfo;
            List<TechCommonChargeItemInfo> bindTechCommonChargeItemList = oi.techCommonChargeItemInfoList.Where(t => t.TechId == workInfo.TechId).ToList();

            if (e.Column.FieldName == "IsUsefull")
            {
                workInfo.IsUsefull = (bool)e.Value;
                if (bindTechCommonChargeItemList.Count > 0)//该节点存在绑定附加收费项目
                {
                    if ((bool)e.Value)
                    {
                        UpdateCommonChargeItems(bindTechCommonChargeItemList, true, oi);
                    }
                    else
                    {
                        UpdateCommonChargeItems(bindTechCommonChargeItemList, false, oi);
                    }
                }
            }
            if (e.Column.FieldName == "UserName")
            {
                workInfo.UserName = e.Value.ToString();
            }

        }

        private void tsbtnModifyPhotoNum_Click_1(object sender, EventArgs e)
        {
            if(gvPhoto.SelectedRowsCount>0)
            {
                FrmPhotoNum frm = new FrmPhotoNum();
                frm.ShowDialog(this);
            }
            else
            {
                MessageBox.Show("请选择您要修改的照片！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        /// <summary>
        /// 修改照片数量
        /// </summary>
        /// <param name="num"></param>
        public void ModifyPhotoNum(int num)
        {
            int [] rowhandels=gvPhoto.GetSelectedRows();
            foreach (var item in rowhandels)
            {
                PhotoInfo photo = gvPhoto.GetRow(item) as PhotoInfo;
                photo.PhotoNum = num;
            }

            gvPhoto.RefreshData();
        }


        // 设置是否检查重复开单
        private void chkCheckRepeatOrder_CheckedChanged(object sender, EventArgs e)
        {
            if (chkCheckRepeatOrder.Checked)
            {
                _presenter.SetCheckCRC(true);
                SetConfig("IsCheckCrcCode", "True");
            }
            else
            {
                _presenter.SetCheckCRC(false);
                SetConfig("IsCheckCrcCode", "False");
            }
        }

        /// <summary>
        /// 修改配置文件中某项的值
        /// </summary>
        /// <param name="key">appSettings的key</param>
        /// <param name="value">appSettings的Value</param>
        private   void SetConfig(string key, string value)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            if (config.AppSettings.Settings[key] != null)
                config.AppSettings.Settings[key].Value = value;
            else
                config.AppSettings.Settings.Add(key, value);

            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }

        /// <summary>
        /// 是否需要Crc验证
        /// </summary>
        private void GetCRCConfig()
        {
            try
            {
                chkCheckRepeatOrder.Checked = System.Configuration.ConfigurationManager.AppSettings["IsCheckCrcCode"].ToUpper() == "TRUE" ? true : false;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void txtShopMnemonicCode_Leave(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            try
            {
                ShopInfo_Order shop = _presenter.ShopList.First(s => s.ShopName == cmbShopList.Text);
                _presenter.BindProductTemplete(shop.ShopId);
                _presenter.BindPaperType(shop.ShopId);
                _presenter.BindPaperFace();
                _presenter.SetCurrentShopInfo(shop);
                _presenter.ClearOrderProduct();
                cmbPriority.Text = shop.Priority.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }


        private void cmbShopList_DropDownClosed(object sender, EventArgs e)
        {
            //Cursor = Cursors.WaitCursor;
            //try
            //{
            //    ShopInfo_Order shop = _presenter.ShopList.First(s => s.ShopName == cmbShopList.Text);
            //    _presenter.BindProductTemplete(shop.ShopId);
            //    _presenter.BindPaperType(shop.ShopId);
            //    _presenter.BindPaperFace();
            //    _presenter.SetCurrentShopInfo(shop);
            //    _presenter.ClearOrderProduct();
            //    cmbPriority.Text = shop.Priority.ToString();
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //}
            //finally
            //{
            //    Cursor = Cursors.Default;
            //}
        }

        private void tsbtnConfig_Click(object sender, EventArgs e)
        {
            FrmConfig frm = new FrmConfig();
            frm.ShowDialog();
        }

        //删除开单目录中的空文件夹
        private void bwDeleteEmptyFolder_DoWork(object sender, DoWorkEventArgs e)
        {
            string orderPath =Properties.Settings.Default.OrderLocalPath;
            if (orderPath != null)
            {
                _presenter.DeleteEmptyOrderFolder(Properties.Settings.Default.OrderLocalPath);
            }
        }

        private void gvOrderProductInfo_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            try
            {
                OrderInfo oi = gvOrderProductInfo.GetRow(e.RowHandle) as OrderInfo;
                if (oi != null)
                {
                    if (e.Column.FieldName == "CtmName")
                    {
                        oi.CtmName = e.Value.ToString();
                    }
                    if (e.Column.FieldName == "Remark")
                    {
                        oi.Remark = e.Value.ToString();
                    }
                    if (e.Column.FieldName == "ProductNum")
                    {
                        oi.ProductNum = Convert.ToInt32(e.Value);
                    }
                    if (e.Column.FieldName == "IsFinishedGoods")
                    {
                        oi.IsFinishedGoods = (bool)e.Value;
                    }
                    if (e.Column.FieldName == "DefaultPrinterName")
                    {
                        oi.DefaultPrinterName = e.Value.ToString();
                    }
                    if (e.Column.FieldName == "DefaultOutShopName")
                    {
                        oi.DefaultOutShopName = e.Value.ToString();
                    }
                    if (e.Column.FieldName == "PapeTypeName")
                    {
                        oi.PapeTypeName = e.Value.ToString();
                    }
                    if (e.Column.FieldName == "PaperFaceName")
                    {
                        oi.PaperFaceName = e.Value.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
 
            }
        }

        private void bwMovePhotoToServer_DoWork(object sender, DoWorkEventArgs e)
        {
            _presenter.MovePhotoToServer();
        }

        private void timerMovePhotoToServer_Tick(object sender, EventArgs e)
        {
            if (!bwMovePhotoToServer.IsBusy)
            {
                bwMovePhotoToServer.RunWorkerAsync();
            }
        }

        private void txtOrderBagCode_Properties_Leave(object sender, EventArgs e)
        {

        }

        private void labelControl6_Click(object sender, EventArgs e)
        {

        }

        private void linkLabelCopy_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Clipboard.SetDataObject(txtOrderBagCode.Text);
        }

        private void xtraTabControl2_Click(object sender, EventArgs e)
        {

        }

        private void tsbtnAddRemark_Click(object sender, EventArgs e)
        {
            List<OrderInfo> orderList = gcOrderProductInfo.DataSource as List<OrderInfo>;
            if (orderList.Count > 0)
            {
                foreach (var oi in orderList)
                {
                    if (!oi.IsAddRemark)
                    {
                        GetRemark(oi);
                    }
                }
                gcOrderProductInfo.RefreshDataSource();
            }
        }

        private void GetRemark(OrderInfo oi)
        {
            DirectoryInfo dir = new DirectoryInfo(oi.OrilOrderPath);
            string remark ="\n";
     
            foreach (var item in dir.GetDirectories())
            {
                List<photoWH> listPhotoWH = new List<photoWH>();

                //int photonum = 0;
                DirectoryInfo subDir = new DirectoryInfo(item.FullName);
                foreach (var file in subDir.GetFiles("*.*", SearchOption.AllDirectories))
                {

                    if (IsImage(file.FullName))
                    {
                        listPhotoWH.Add(GetphotoWH(file.FullName));
                        //photonum++;
                    }
                }
                
                //remark += item.Name + " X " + photonum + "\n";
                remark += item.Name+"\n";
                foreach (var photoWH in listPhotoWH.GroupBy(p=>p.WH))
                {
                    remark += photoWH.First().WH + " X " + photoWH.Count() + "\n";
                }
            }
            foreach (FileInfo item in dir.GetFiles())
            {
                if (IsImage(item.FullName))
                {
                    photoWH wh = GetphotoWH(item.FullName);
                    remark += item.Name+"\n";
                    remark += wh.WH + "X 1" + "\n";
                }
            }
            oi.Remark += remark;
            oi.IsAddRemark = true;
        }

        private photoWH GetphotoWH(string path)
        {

            CodecsImageInfo imgInfo = codecs.GetInformation(path, true);

            double width = (float)imgInfo.Width / imgInfo.XResolution*2.54;
            double heigh = (float)imgInfo.Height / imgInfo.YResolution*2.54;

            return new photoWH{ WH = width.ToString("0.00") +"X"+ heigh.ToString("0.00")};

        }
          
        private bool IsImage(string filePath)
        {
            //Image oImg;
            //try
            //{
            //    oImg =Image.FromFile(filePath);
            //    oImg.Dispose();
            //    return true;


            //}
            //catch
            //{
            //    return false;
            //}

            FileInfo file = new FileInfo(filePath);
            if (file.Extension.ToUpper() == ".JPG" || file.Extension.ToUpper() == ".JPEG" || file.Extension.ToUpper() == ".TIF" | file.Extension.ToUpper() == ".TIFF")
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private void gvPhoto_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator && e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        private void toolStripButtonSaveFormat_Click(object sender, EventArgs e)
        {
            try
            {
                gvOrderProductInfo.SaveLayoutToXml(Application.StartupPath + "\\Layout\\StartOrdergvProductList.Xml");
                gvPhoto.SaveLayoutToXml(Application.StartupPath + "\\Layout\\StartOrdergvProduct.Xml");
                MessageBox.Show("表格格式保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
            catch
            {
                MessageBox.Show("格式未保存成功，请重新尝试", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }

        private void browser1_SelectedFolderChanged(object sender, WHFileBrowser.SelectedFolderChangedEventArgs e)
        {

        }

        private void browser1_SelectedHasChanged(string[] paths)
        {
            _splitFilePath = paths.ToList();
            gvPhoto.ClearSelection();
            
            if (gcPhotoInfo.DataSource != null)
            {
                for (int i = 0; i < paths.Length; i++)
                {
                    for (int j = 0; j < gvPhoto.RowCount; j++)
                    {
                        PhotoInfo pi = (PhotoInfo)gvPhoto.GetRow(j);
                        if (pi.OldPicPath.Contains(paths[i]+"\\"))
                        {
                            gvPhoto.SelectRow(j);
                        }
                    }
                   
                }
            }

        }

        private void gvOrderProductInfo_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {

        }

        


        #region 验证设计时尺寸和P数
        //public bool CheckSizeAndPage(OrderInfo currProduct)
        //{
        //    FrmCheckSizeAndPage frmCheckSizeAndPage = new FrmCheckSizeAndPage(currProduct);
        //    frmCheckSizeAndPage.PageNum = currProduct.ProductModel.PageNum;
        //    frmCheckSizeAndPage.Width = currProduct.ProductModel.Width;
        //    frmCheckSizeAndPage.Height = currProduct.ProductModel.Height;
        //    frmCheckSizeAndPage.SizeUnit = "英寸(in)";
        //    currProduct.isn = true;
        //    if (DialogResult.OK == frmCheckSizeAndPage.ShowDialog())
        //    {

        //        //spinPageNum.Text = frmCheckSizeAndPage.PageNum.ToString();

        //        //spinHeight.Tag = frmCheckSizeAndPage.Height;
        //        //spinWidth.Tag = frmCheckSizeAndPage.Width;
        //        //cbUnit.Text = frmCheckSizeAndPage.SizeUnit;
        //        //spinPageNum.Value = frmCheckSizeAndPage.PageNum;//需要设计的产品安装输入计算
        //        currProduct.IsCheckStyle = true;

        //        return true;
        //    }
        //    else
        //    {
        //        currProduct.IsCheckStyle = false;
        //        return false;
        //    }

        //}
        #endregion


        public void GetAllPicByDir(string inPath, List<string> inList)
        {
 
            string picTag = ".JPEG.JPG.TIF.BMP.TIFF";
            DirectoryInfo rootDir = new DirectoryInfo(inPath);
            if (rootDir.Exists)
            {
                FileInfo[] fileList = rootDir.GetFiles();
                foreach (FileInfo info in fileList)
                {
                    if (picTag.Contains(info.Extension.ToUpper()))
                    {
                        inList.Add(info.FullName);
                    }
                    else
                    {
                        if (info.FullName.ToUpper().IndexOf(("Thumbs.db").ToUpper()) == -1)
                        {
                            inList.Add(info.FullName);
                        }
                    }
                }
                DirectoryInfo[] listDir = rootDir.GetDirectories();
                foreach (DirectoryInfo dir in listDir)
                {
                    GetAllPicByDir(dir.FullName, inList);
                }
            }

        }
        #region  拆分文件
        private List<string> _splitFilePath;
        private FrmProcessBarProcessingfile barProcessFile;

        private void tsbtnSplit_Click(object sender, EventArgs e)
        {
            if (DialogResult.OK == MessageBox.Show("确定拆分选定文件夹吗？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
            {
                if (_splitFilePath.Count > 0)
                {
                    foreach (var item in _splitFilePath)
                    {
                        if (Directory.Exists(item))
                        {
                            bwSplit.RunWorkerAsync(item);
                            barProcessFile = new FrmProcessBarProcessingfile();
                            barProcessFile.ShowDialog();
                        }
                        else
                        {
                            MessageBox.Show("选定的目录无法访问！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }

                    }
                    _splitFilePath.Clear();//
                }

            }
        }

        private void tsbtnMerge_Click(object sender, EventArgs e)
        {
            if (DialogResult.OK == MessageBox.Show("确定合并选定文件夹吗？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
            {
                if (_splitFilePath.Count > 0)
                {
                    foreach (var item in _splitFilePath)
                    {
                        if (Directory.Exists(item))
                        {
                            bwMerge.RunWorkerAsync(item);
                            barProcessFile = new FrmProcessBarProcessingfile();
                            barProcessFile.ShowDialog();
                        }
                        else
                        {
                            MessageBox.Show("选定的目录无法访问！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }

                    }
                    _splitFilePath.Clear();//
                }

            }
        }

        private void bwMerge_DoWork(object sender, DoWorkEventArgs e)
        {
            MergeFile((string)e.Argument, sender, e);
        }

        private void MergeFile(string  dirpath, object sender, DoWorkEventArgs e)
        {

                if (!Directory.Exists(dirpath))
                {
                    bwMerge.ReportProgress(-1, "文件夹不存在");
                    return;
                }

                List<string> FileFullNameList = new List<string>();

                GetAllPicByDir(dirpath, FileFullNameList);
                int Count = FileFullNameList.Count();
                int iCount = 0;
                string currPath = dirpath.Substring(dirpath.LastIndexOf("\\"));
                foreach (string strFilePath in FileFullNameList)
                {
                    iCount++;
                    bwMerge.ReportProgress(1, ((decimal)iCount * 100 / Count).ToString("0"));
                    string sourcePath = strFilePath;

                    string temp = strFilePath.Substring(dirpath.Length + 1);
                    if (string.IsNullOrEmpty(temp) || temp.IndexOf("\\") < 0)
                    {
                        continue;
                    }
                    string toTempPath = strFilePath.Substring(dirpath.Length).Replace("\\", "-");
                    string toPath = dirpath + "\\" + toTempPath;
                    File.Move(sourcePath, toPath);

                }
                bwMerge.ReportProgress(10, "");
            
           
        }

        private void bwMerge_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (e.ProgressPercentage == 1)
            {
                barProcessFile.progressBar.Value = Convert.ToInt32(e.UserState);

            }
            else if (e.ProgressPercentage == 10)
            {
                MessageBox.Show("整理完成");
            }
            else
            {
                MessageBox.Show(e.UserState.ToString());
            }
        }


        #endregion

        private void bwMerge_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
      
            barProcessFile.Close();
            barProcessFile.Dispose();
        }

        private void bwSplit_DoWork(object sender, DoWorkEventArgs e)
        {
            SplitFile((string)e.Argument, sender, e);
        }

        private void bwSplit_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (e.ProgressPercentage == 1)
            {
                barProcessFile.progressBar.Value = Convert.ToInt32(e.UserState);

            }
            else if (e.ProgressPercentage == 10)
            {
                MessageBox.Show("整理完成");
            }
            else
            {
                MessageBox.Show(e.UserState.ToString());
            }
        }

        private void bwSplit_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            barProcessFile.Close();
            barProcessFile.Dispose();
        }

        private void SplitFile(string dirpath, object sender, DoWorkEventArgs e)
        {

            if (!Directory.Exists(dirpath))
            {
                bwSplit.ReportProgress(-1, "文件夹不存在");
                return;
            }

            List<string> FileFullNameList = new List<string>();

            GetAllPicByDir(dirpath, FileFullNameList);
            int Count = FileFullNameList.Count();
            int iCount = 0;
            string currPath = dirpath.Substring(dirpath.LastIndexOf("\\"));
            foreach (string strFilePath in FileFullNameList)
            {
                iCount++;
                bwSplit.ReportProgress(1, ((decimal)iCount * 100 / Count).ToString("0"));
                string sourcePath = strFilePath;
                
                string strfileUpdirPath = strFilePath.Substring(0,strFilePath.LastIndexOf("\\"));//照片的上一层文件夹路径
                string strfileUpdirName = strfileUpdirPath.Substring(strfileUpdirPath.LastIndexOf("\\") + 1);//文件名称
                string strfileName = strFilePath.Substring(strFilePath.LastIndexOf("\\") + 1);//文件名称

                string strtempPath = strfileUpdirPath.Substring(0,strfileUpdirPath.LastIndexOf("\\"));//照片的上2层文件夹路径

                string strToPath = strtempPath + "\\" + strfileUpdirName + "_" + strfileName.Substring(0,strfileName.LastIndexOf(".")) + "\\" + strfileName;
                if (!Directory.Exists(strtempPath + "\\" + strfileUpdirName + "_" + strfileName.Substring(0, strfileName.LastIndexOf("."))))
                {
                    Directory.CreateDirectory(strtempPath + "\\" + strfileUpdirName + "_" + strfileName.Substring(0, strfileName.LastIndexOf(".")));
                }

                File.Move(sourcePath, strToPath);

            }
            bwSplit.ReportProgress(10, "");


        }

        private void txtOrderBagCode_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            _presenter.bagCode = e.NewValue.ToString();
        }

        private void gvPhoto_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            try
            {
                PhotoInfo pi = gvPhoto.GetRow(e.RowHandle) as PhotoInfo;
                if (e.Column.FieldName == "PhotoNum")
                {
                    pi.PhotoNum = Convert.ToInt32(e.Value);
                }
            }
            catch
            {
                MessageBox.Show("请输入整数！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void cmbPrinter_SelectedIndexChanged(object sender, EventArgs e)
        {

            if (gcOrderProductInfo.DataSource != null)
            {
                foreach (var orderInfo in ((List<OrderInfo>)gcOrderProductInfo.DataSource).ToList())
                {
                    orderInfo.DefaultPrinterName = cmbPrinter.Text;
                    foreach (var photo in orderInfo.Photos)
                    {
                        photo.PrinterName = cmbPrinter.Text;
                    }
                }
                gcOrderProductInfo.RefreshDataSource();
                gcPhotoInfo.RefreshDataSource();
            }
        }

        private void gvPhoto_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            if(e.RowHandle>=0)
            {
                PhotoInfo pi = (PhotoInfo)gvPhoto.GetRow(e.RowHandle);

                if (pi!=null&&pi.isNotSizeInProduct)
                {
                    e.Appearance.BackColor = Color.Red;
                }
            }
            
            
        }




        

    }

    public class photoWH
    {
        public string WH { get; set; }
    }
}
